﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _5._06处理异步操作中的异常
{
    class Program
    {
        static void Main(string[] args)
        {
            Task t = AsynchronousProcessing();
            t.Wait();
            Console.ReadLine();
        }

        private async static Task AsynchronousProcessing()
        {

            Console.WriteLine("1. Single exception");

            try
            {
                string result = await GetInfoAsync("Task 1", 3);
                Console.WriteLine(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception details: {ex}");
            }
            Console.WriteLine();
            Console.WriteLine("1. Mutiple exceptions");

            Task<string> t1 = GetInfoAsync("Task 1", 3);
            Task<string> t2 = GetInfoAsync("Task 2", 5);
            try
            {
                string[] results = await Task.WhenAll(t1, t2);
                Console.WriteLine(results.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception details: {ex}");
            }

            Console.WriteLine();
            Console.WriteLine("2. Mutiple exceptions with AggregateException");

            t1 = GetInfoAsync("Task 1", 3);
            t2 = GetInfoAsync("Task 2", 5);
            Task<string[]> t3 = Task.WhenAll(t1, t2);
            try
            {
                string[] results = await t3;
                Console.WriteLine(results.Length);
            }
            catch (Exception)
            {
                var ae = t3.Exception.Flatten();
                var exceptions = ae.InnerExceptions;
                Console.WriteLine($"Exceptions caught: {exceptions.Count}");
                foreach (var e in exceptions)
                {
                    Console.WriteLine($"Exception details: {e}");
                    Console.WriteLine();
                }
            }
        }

        private async static Task<string> GetInfoAsync(string name, int seconds)
        {
            await Task.Delay(TimeSpan.FromSeconds(seconds));
            throw new Exception($"Boom from {name}! ");
        }
    }
}
